package com.example.carborrow.Interceptor;

import com.sun.org.apache.xerces.internal.impl.xs.identity.XPathMatcher;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;




public class LoginInterceptor implements HandlerInterceptor {


    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getRequestURI().endsWith(".css") || request.getRequestURI().endsWith(".js")) {
            // CSS  js 文件直接放行
            return true;
        }
        String requestURI = request.getRequestURI();

//        //访问login.html , /  已登录-> xxx_home.html
//        if (MatchLoginUrl(requestURI))
//        {
//            if(LoggedIn(request) ==1) {
//                response.sendRedirect("/cars/admin_home");
//            }
//            else if(LoggedIn(request) ==2){
//                response.sendRedirect("/cars/customer_home");
//            }
//        }
//        // 访问"/**".exclude(login.html )  未登录-> login.html
//        else {
//            if(LoggedIn(request)==0) {
//
//            }
//        }
        int type = LoggedIn(request);
        if(type == 0 ) {//未登录
            if(!MatchLoginUrl(requestURI)) {
                response.sendRedirect("/login.html");
                return false;
            }
        }
        //已登录
        else if(MatchLoginUrl(requestURI)) { //访问login
            response.sendRedirect("/cars/"+(type==1?"admin_home":"customer_home"));
        }
        else {
            if(type == 1 && requestURI.startsWith("/cars/customer")){
                response.sendRedirect("/cars/admin_home");
                return false;
            }
            else if(type == 2 && requestURI.startsWith("/cars/admin")) {
                response.sendRedirect("/cars/customer_home");
                return false;
            }
        }


        return true;
    }


    //检查已登录
    // session不为空 且 user属性存在 则返回 true
//    private boolean LoggedIn(HttpServletRequest request) {
//        HttpSession session = request.getSession(false);
//        return session != null && session.getAttribute("user")!=null;
//    }

    private int LoggedIn(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        int state = 0 ;
        if(session != null && session.getAttribute("user")!=null)
        {
            if(session.getAttribute("loginType") .equals("admin")) {
                state = 1;
            }
            else { //customer
                state = 2;
            }
        }
        return state;
    }

    private boolean MatchLoginUrl(String requestURI)
    {
        return( pathMatcher.match("/login.html",requestURI)|| pathMatcher.match("/",requestURI));
    }

}
